﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Client;

namespace Kocic.RepositoryManagement.Crm4
{
    /// <summary>
    /// Handles XRM caching for CRM entities.
    /// </summary>
    public class XrmCacheManager : IDisposable
    {
        private const String format = "adxdependency:crm:entity:{0}";
        private Boolean _disposed = false;
        private static XrmCacheManager _cachingInstance;

        /// <summary>
        /// Creates an instance of the XrmCacheManager class.
        /// </summary>
        public XrmCacheManager()
        {
            _cachingInstance = this;
        }

        /// <summary>
        /// Gets or sets a static reference to the the XrmCacheManager type.
        /// </summary>
        public static XrmCacheManager CachingInstance
        {
            get { return XrmCacheManager._cachingInstance; }
            set { XrmCacheManager._cachingInstance = value; }
        }

        /// <summary>
        /// Clears the cache for the specified CRM entity of type TCrmEntityObject.
        /// </summary>
        public static void ClearCache<TCrmEntityObject>()
            where TCrmEntityObject : CrmEntity
        {
            String dependency = string.Format(format, typeof(TCrmEntityObject).Name).ToLower();
            var cache = Microsoft.Xrm.Client.Caching.CacheManager.GetBaseCache();
            cache.Remove(dependency);
        }

        #region IDisposable Members

        /// <summary>
        /// Releases resouces used by the data source deferrer.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        /// <summary>
        /// Disposes unmanaged resources.
        /// </summary>
        /// <param name="disposing">Value indicating if to invoke the method from the IDisposable.Dispose implementation or from the finalizer.</param>
        protected virtual void Dispose(Boolean disposing)
        {
            if (disposing)
            {
                this._disposed = true;
            }
        }
    }
}